package com.ch.d0627;

import com.ch.bean.Result;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "Upload1Servlet", value = "/Upload1Servlet")
public class Upload1Servlet extends HttpServlet {
    public static final String UPLOAD_DIR = "";

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //假设上传文件字段 file
        Part filePart = request.getPart("file");
        //构建文件对象
        String diskPath = UPLOAD_DIR + filePart.getSubmittedFileName();
        File fileObj = new File(diskPath);

        //获取响应流
        PrintWriter out = response.getWriter();
        response.setContentType("application/json;charset=utf-8");
        //判断文件是否存在
        if(fileObj.exists()){
            Result res =  new Result(0,"文件已经存在，上传失败!",null);
            String json = new Gson().toJson(res);
            out.write(json);
        }else {
            filePart.write(diskPath);
            Result res = new Result(1,"文件上传成功!",null);
            String json = new Gson().toJson(res);
            out.write(json);
        }
    }
}
